/**
 * 
 */
package ua.amsoft.brelok.task;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.message.BasicHeader;

import ua.amsoft.brelok.dao.UserInputDocsReportsDAO;
import ua.amsoft.brelok.db.DatabaseOpenHelper;
import ua.amsoft.brelok.manager.HttpManager;
import ua.amsoft.brelok.util.DateTimeUtils;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.common.io.ByteStreams;

/**
 * @author Tair_Mustafaiev
 * 
 */
public class FetchAndUpdateUIDRTask extends AsyncTask<String, Void, InputStream> {
    
    private static final String TAG = FetchAndUpdateUIDRTask.class.getCanonicalName();
    
    private final UserInputDocsReportsDAO dao;
    
    public FetchAndUpdateUIDRTask(final Context context) {
        this.dao = new UserInputDocsReportsDAO(context);
    }
    
    @Override
    protected InputStream doInBackground(final String... params) {
        final HttpManager manager = new HttpManager();
        final Header header = new BasicHeader("Content-Type", "application/xml");
        final HttpResponse response = manager.doGet(
                "http://csvr-vm-249.am-soft.net.ua/api/reports/ReportUserInputDocs/2012-09-11/2012-09-11/1", header);
        if (response != null) {
            try {
                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    final InputStream is = response.getEntity().getContent();
                    this.insertToDb(is);
                }
            } catch (final IllegalStateException e) {
                Log.e(FetchAndUpdateUIDRTask.TAG, e.getLocalizedMessage());
            } catch (final IOException e) {
                Log.e(FetchAndUpdateUIDRTask.TAG, e.getLocalizedMessage());
            }
        }
        return null;
    }
    
    /**
     * Inserts and {@link InputStream} fetched to database
     * 
     * @param result
     *            - fetched {@link InputStream}
     */
    private void insertToDb(final InputStream result) {
        final ContentValues values = new ContentValues();
        try {
            final byte[] file = ByteStreams.toByteArray(result);
            values.put(DatabaseOpenHelper.UIDR_DATE_UPDATED_COLUMN, DateTimeUtils.formatInputDate(new Date()));
            values.put(DatabaseOpenHelper.UIDR_FILE_COLUMN, file);
            this.dao.forceUpdateTable(values);
        } catch (final IOException e) {
            Log.e(FetchAndUpdateUIDRTask.TAG, e.getLocalizedMessage());
        }
    }
    
}
